// 对应的是readyState的4，不过由于等号右边是MDN推荐写法
// 所以定义一个常量done用于引用
const done = XMLHttpRequest.DONE;

function ajax(method, url){
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.open(method, url);
        request.onreadystatechange = () => {
            if (request.readyState === done){
                if (request.status === 200){
                    resolve(request.response);
                }else{
                    reject(request);
                }
            }
        };

        request.send();
    });
};

ajax('get', "http://localhost:5000/friends.json")
    .then(response => {
        console.log('This is AJAX');
        console.log(response);
    });


function jsonp(url){
    // JSONP的写法
    return new Promise((resolve, reject) => {
        const random = 'AllenJsonpCallback' + Math.random();
        window[random] = data =>{ resolve(data) };

        // create a <script> tag
        const script = document.createElement('script');
        script.src = `${url}?callback=${random}`;

        // when the script loaded, the tag should be removed.
        script.onload = () => {
            script.remove();
        };

        script.onerror = () => {
            reject();
        };

        document.body.appendChild(script);
    });
};

jsonp('http://localhost:5000/friends.js')
    .then(data => {
        console.log(data);
    });